import axios from 'axios'
import ala from 'ala'

export async function httpGetError(apiUrl, data) {
  var request
  await axios.get(ala.host + apiUrl, {
    params: data,
    headers: ala.header(apiUrl)
  }).then(function (res) {
    request = res
  }).catch(function (error) {
    console.error('错误:' + error)
  })
  return request
}



export async function httpGet(apiUrl, data) {
  var request
  await axios.get(ala.host + apiUrl, {
    params: data,
    headers: ala.header(apiUrl)
  }).then(function (res) {
    request = res
  }).catch(function (error) {
    errorResult(error, apiUrl)
  })
  var response = result(request, apiUrl)
  return response
}

export async function httpId(apiUrl, id) {
  var response = await httpGet(apiUrl, { id: id })
  return response
}

export async function httpPost(apiUrl, data) {
  var request
  await axios.post(ala.host + apiUrl, data, {
    headers: ala.header(apiUrl)
  }).then(function (res) {
    request = res
  }).catch(function (error) {
    errorResult(error, apiUrl)
  })
  var response = result(request, apiUrl)
  return response
}
//  Put方法：改
export async function httpPut(apiUrl, data) {
  var request
  await axios.put(ala.host + apiUrl, data, {
    headers: ala.header(apiUrl)
  }).then(function (res) {
    request = res
  }).catch(function (error) {
    errorResult(error, apiUrl)
  })
  var response = result(request, apiUrl)
  return response
}
export async function httpDelete(apiUrl, data) {
  var request
  var para = parseParams(data)
  if (para) {
    apiUrl += '?' + para
  }
  await axios.delete(ala.host + apiUrl, {
    // params: data,
    headers: ala.header(apiUrl)
  }).then(function (res) {
    request = res
  }).catch(function (error) {
    errorResult(error, apiUrl)
  })
  var response = result(request, apiUrl)
  return response
}

function parseParams(data) {
  try {
    var tempArr = []
    for (var i in data) {
      var key = encodeURIComponent(i)
      var value = encodeURIComponent(data[i])
      tempArr.push(key + '=' + value)
    }
    var urlParamsStr = tempArr.join('&')
    return urlParamsStr
  } catch (err) {
    return ''
  }
}

function errorResult(error, apiUrl) {
  if (error.request && error.request.status === 404) {
    ala.error('接口未找到' + apiUrl)
  }
  if (error.response && error.response.data) {
    ala.error(error.response.data.message)
  }
}

function result(response, apiUrl) {
  if (response && response.status === 200) {
    if (response.data.status === 1) {
      if (response.data.result) {
        return response.data.result
      } else {
        return response.data
      }
    } else {
      ala.error(response.data.message)
      return null
    }
  }
  if (response && response.status === 400) {
    ala.error('404错误：' + ala.host + apiUrl)
  }
}
